package com.linkage.seapeak.activity.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.swipeitemlayout.BGASwipeItemLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PersonalAddressActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    List<MyAddr> mDataList;
    AYSwipeRecyclerView recyclerView;
    BaseRecyclerAdapter adapter;
    Bitmap often;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_address, "我的地址");
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_often);
        often = Bitmap.createScaledBitmap(bitmap, dp2px(35), dp2px(18), true);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        mDataList = new ArrayList<>();
        recyclerView = findViewById(R.id.address_list);
        recyclerView.setOnRefreshLoadLister(this);
        recyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        /**
         * 打标记！！！新增地址的入口，防止后期需求
         */
//        addMenu(new MenuAction(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent i = new Intent(PersonalAddressActivity.this, CreateAddrActivity.class);
//                //返回数据
//                startActivity(i);
//            }
//        }, "新增", 0));

        adapter = new BaseRecyclerAdapter<ViewHolder>() {
            @NonNull
            @Override
            public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                return new ViewHolder(LayoutInflater.from(PersonalAddressActivity.this)
                        .inflate(R.layout.item_personal_address, viewGroup, false));
            }

            @Override
            public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
                final MyAddr myAddr = mDataList.get(i);
                if (myAddr != null) {
                    if(BankruptcyApp.loginInfo!=null)
                        viewHolder.title.setText(BankruptcyApp.loginInfo.getUsername());

                    String desc = "";
                    desc += myAddr.province + myAddr.city + myAddr.region;
                    desc += myAddr.address;
                    viewHolder.desc.setText(desc);
                    if (myAddr.isDefaut()) {
                        ImageSpan imgSpan = new ImageSpan(PersonalAddressActivity.this, often);
                        SpannableString spannableString = new SpannableString(" often");
                        spannableString.setSpan(imgSpan, 1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        viewHolder.desc.append(spannableString);
                    }
                    viewHolder.setOften.setText(myAddr.isDefaut() ? "取消默认" : "设为默认");
                    viewHolder.setOften.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            myAddr.setDefaut(!myAddr.isDefaut());
                            updateAddress(myAddr);
                        }
                    });
                    viewHolder.edit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            viewHolder.itemLayout.closeWithAnim();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent = new Intent(PersonalAddressActivity.this, CreateAddrActivity.class);
                                    intent.putExtra("item", myAddr);
                                    startActivity(intent);
                                }
                            }, 200);
                        }
                    });
                    viewHolder.delete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDataList.remove(i);
                            viewHolder.itemLayout.closeWithAnim();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    delAddress(myAddr);
                                }
                            }, 200);
                        }
                    });
                }
            }

            @Override
            public int getItemCount() {
                return mDataList.size();
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.startLoadFirst();
    }

    @Override
    public void loadFirst() {
        getData();
    }

    @Override
    public void loadNext() {}

    @Override
    protected void onResume() {
        super.onResume();
        recyclerView.startLoadFirst();
    }

    class ViewHolder extends BaseHolder {

        BGASwipeItemLayout itemLayout;
        TextView title, desc;
        View delete, edit;
        TextView setOften;

        public ViewHolder(View view) {
            super(view);
            itemLayout = view.findViewById(R.id.sil_item_bgaswipe_root);
            title = view.findViewById(R.id.title);
            desc = view.findViewById(R.id.desc);
            delete = view.findViewById(R.id.delete);
            edit = view.findViewById(R.id.edit);
            setOften = view.findViewById(R.id.setOften);
        }
    }

    /**
     * 删除地址
     * @param myAddr
     */
    public void delAddress(MyAddr myAddr) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        Network.getAPIService()
                .delAddress(getUserToken(), myAddr.id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        } else
                            loadFirst();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    /**
     * 更新地址
     * @param myAddr
     */
    public void updateAddress(MyAddr myAddr) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        Network.getAPIService()
                .setDefaultAddress(getUserToken(), myAddr.id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        } else {
                            showToast("设置成功");
                            loadFirst();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    /**
     * 获取网络数据
     */
    public void getData() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userId", userId)
                .add("userToken", userToken)
                .build();

        String url = Consts.WEBURL_GETADDR;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    //
                    @Override
                    public void run() {
                        //更新UI
                        recyclerView.onFinishRequest(true, false);
                    }

                });
            }

            @Override
            public void onResponse(Call call, final Response response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String str = response.body().string();
                            JSONObject object = new JSONObject(str);
                            mDataList.clear();
                            if (object.optInt("code") == 0) {
//                        JSONObject data = object.getJSONObject("data");
                                JSONArray ary = object.getJSONArray("data");
                                for (int i = 0; i < ary.length(); i++) {
                                    JSONObject data = ary.getJSONObject(i);
                                    MyAddr model = new MyAddr();
                                    model.setId(data.getString("id"));
                                    model.setAddress(data.getString("address"));
                                    model.setCity(data.getString("city"));
                                    model.setDefaut(data.getBoolean("defaut"));
                                    model.setProvince(data.getString("province"));
                                    model.setRegion(data.getString("region"));
                                    model.setZipCode(data.getString("zipCode"));
                                    mDataList.add(model);
                                }
                                //更新UI
                                recyclerView.onFinishRequest(false, false);
                                return;
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        //更新UI
                        recyclerView.onFinishRequest(true, false);
                    }
                });
            }
        });
    }
}
